package com.fc.mall.controller;

import com.fc.mall.base.object.Result;
import com.fc.mall.dto.*;
import com.fc.mall.exception.InternalServerErrorException;
import com.fc.mall.kdniao.constants.Shipper;
import com.fc.mall.kdniao.domain.LogisticTraceReq;
import com.fc.mall.kdniao.domain.LogisticTraceResp;
import com.fc.mall.kdniao.service.KDNiaoService;
import com.fc.mall.model.OmsOrder;
import com.fc.mall.service.OmsOrderService;
import com.fc.mall.dto.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单管理Controller
 * Created by dobuy on 2018/10/11.
 */
@Controller
@Api(tags = "OmsOrderController", description = "订单管理")
@RequestMapping("/order")
public class OmsOrderController {
    @Autowired
    private OmsOrderService orderService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private KDNiaoService kdNiaoService;

    @ApiOperation("查询订单")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(OmsOrderQueryParam queryParam,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                       @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<OmsOrder> orderList = orderService.list(queryParam, pageSize, pageNum);
        return new CommonResult().pageSuccess(orderList);
    }

    @ApiOperation("批量发货")
    @RequestMapping(value = "/update/delivery", method = RequestMethod.POST)
    @ResponseBody
    public Object delivery(@RequestBody List<OmsOrderDeliveryParam> deliveryParamList) {
        int count = orderService.delivery(deliveryParamList);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation("批量关闭订单")
    @RequestMapping(value = "/update/close", method = RequestMethod.POST)
    @ResponseBody
    public Object close(@RequestParam("ids") List<Long> ids, @RequestParam String note) {
        int count = orderService.close(ids, note);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation("批量删除订单")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(@RequestParam("ids") List<Long> ids) {
        int count = orderService.delete(ids);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation("获取订单详情:订单信息、商品信息、操作记录")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object detail(@PathVariable Long id) {
        OmsOrderDetail orderDetailResult = orderService.detail(id);
        return new CommonResult().success(orderDetailResult);
    }

    @ApiOperation("修改收货人信息")
    @RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) {
        int count = orderService.updateReceiverInfo(receiverInfoParam);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation("修改订单费用信息")
    @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) {
        int count = orderService.updateMoneyInfo(moneyInfoParam);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation("备注订单:  status仅此处特殊处理表示订单备注旗子颜色:  1:红  2：灰  3：绿  4：蓝  5：紫")
    @RequestMapping(value = "/update/note", method = RequestMethod.POST)
    @ResponseBody
    public Object updateNote(@RequestParam("id") Long id,
                             @RequestParam("note") String note,
                             @RequestParam("status") Integer status) {
        int count = orderService.updateNote(id, note, status);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation("根据条件导出订单")
    @RequestMapping(value = "/exportXls", method = RequestMethod.GET)
    public void exportXls(OmsOrderQueryParam queryParam, HttpServletResponse response, Principal principal) {
        List<OmsOrderItemDetail> orderItemDetails = orderService.getAllOrderItemDetails(queryParam);
        List<OmsOrderItemExcel> orderItemExcels = orderItemDetails
                .stream().flatMap(orderItemDetail -> orderItemDetail.getOrderItemList()
                        .stream().map(omsOrderItem -> {
                            OmsOrderItemExcel orderItemExcel = mapperFacade.map(omsOrderItem, OmsOrderItemExcel.class);
                            orderItemExcel.setSp(nullToEmpty(omsOrderItem.getSp1())
                                    + nullToEmpty(omsOrderItem.getSp2())
                                    + nullToEmpty(omsOrderItem.getSp3()));
                            orderItemExcel.setCreateTime(orderItemDetail.getCreateTime());
                            orderItemExcel.setNote(orderItemDetail.getNote());
                            orderItemExcel.setStatus(orderItemDetail.getStatus());
                            orderItemExcel.setReceiver(orderItemDetail.getReceiverName());
                            orderItemExcel.setReceiverAddress(orderItemDetail.getReceiverProvince() + orderItemDetail.getReceiverCity() + orderItemDetail.getReceiverRegion() + orderItemDetail.getReceiverDetailAddress());
                            orderItemExcel.setPaymentAmount(orderItemDetail.getPayAmount());
                            orderItemExcel.setPhone(orderItemDetail.getReceiverPhone());
                            try {
                                if(!StringUtils.isEmpty(orderItemDetail.getMemberUsername()))
                                {
                                    orderItemExcel.setNickname(URLDecoder.decode(orderItemDetail.getMemberUsername(), "utf-8"));
                                }
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            return orderItemExcel;
                        })).collect(Collectors.toList());
        response.setHeader("Content-disposition", "attachment; filename=order.xls");
        response.setHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        try {
            String  username = principal.getName();
            ExcelExportUtil.exportExcel(new ExportParams("订单列表", "生成人:" + username, "订单信息"),
                    OmsOrderItemExcel.class, orderItemExcels).write(response.getOutputStream());
        } catch (IOException e) {
            throw new InternalServerErrorException("生成报表失败");
        }
    }

    @ApiOperation("根据订单号查询订单物流信息")
    @RequestMapping("/trackLogisticByOrderId/{orderId}")
    @ResponseBody
    public Result trackLogisticByOrderId(@PathVariable Long orderId) {
        OmsOrder omsOrder = orderService.detail(orderId);
        if (omsOrder != null && omsOrder.getDeliveryCompany() != null && omsOrder.getDeliverySn() != null) {
            LogisticTraceReq req = new LogisticTraceReq();
            req.setShipperCode(Shipper.getCode(omsOrder.getDeliveryCompany()));
            req.setLogisticCode(omsOrder.getDeliverySn());
            LogisticTraceResp resp = kdNiaoService.trackLogistic(req);
            resp.setShipperName(omsOrder.getDeliveryCompany());
            return Result.success(resp);
        } else {
            return Result.failed("订单无物流信息");
        }
    }

    @ApiOperation("根据订单号查询分佣情况")
    @RequestMapping("/cent/commission/{orderId}")
    @ResponseBody
    public Result CentCommossionByOrder(@PathVariable Long orderId)
    {
        List<OmsCentCommossion> omsCentCommossionList = orderService.queryCentCommossionByOrderId(orderId);

        return Result.success(omsCentCommossionList);
    }

    @ApiOperation("获取粉丝订单")
    @GetMapping("{memberId}/fans")
    @ResponseBody
    public CommonResult handleGetMemberFansOrders(@PathVariable Long memberId,
                                                  @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum)
    {
        List<OmsOrder> fansOrders = orderService.getFansOrderList(memberId, pageNum, pageSize);
        return new CommonResult().pageSuccess(fansOrders);
    }

    private String nullToEmpty(String str) {
        return str == null ? "" : str;
    }
}
